package com.shuimuzhen.SecondhandMotorManagementSystem.websocket;

import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.HashMap;
import java.util.Map;

@Component
@ServerEndpoint("/ws/{id}")
public class webSocketServer {

    //存会话对象
    private static Map<String, Session> sessionMap = new HashMap<>();
    @OnOpen
    public void onOpen(Session session, @PathParam("id")String id){
        System.out.println(id+"open Session");
        sessionMap.put(id,session);
    }

    @OnMessage
    public void onMessage(String message, @PathParam("id")String id){
        System.out.println(id+"send message"+message);
    }

    @OnClose
    public void onClose(@PathParam("id")String id){
        System.out.println(id+"close");
        sessionMap.remove(id);
    }

    public void sendToAll(String message){
        Collection<Session> sessions = sessionMap.values();
        for (Session session : sessions){
            try{
                //服务器向客户端发消息
                session.getBasicRemote().sendText(message);
            } catch (Exception e){
                e.printStackTrace();
            }
        }
    }
}




